package com.gitee.cui.springcloud.controller;

import javax.annotation.Resource;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.gitee.cui.springcloud.entities.CommonResult;
import com.gitee.cui.springcloud.entities.Payment;
import com.gitee.cui.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * TODO
 *
 * @author cuiqingqiang
 * @version 1.0
 * @date 2022-03-20 12:35
 **/
@RestController
@Slf4j
@RequestMapping("/consumer")
public class CircleBreakerController {

	@Value("${service-url.nacos-user-service}")
	private String serviceUrl;

	@Resource
	private RestTemplate restTemplate;

	@GetMapping("/fallback/{id}")
	// @SentinelResource(value = "fallback")
	// @SentinelResource(value = "fallback", blockHandler = "blockHandler")
	// @SentinelResource(value = "fallback", fallback = "handlerFallback")
	@SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler",
			exceptionsToIgnore = {IllegalArgumentException.class})
	public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
		CommonResult<Payment> result = restTemplate.getForObject(serviceUrl + "/payment/" + id, CommonResult.class, id);
		if (id == 4) {
			throw new IllegalArgumentException("IllegalArgumentException, 非法参数异常");
		} else if (result.getData() == null) {
			throw new NullPointerException("NullPointerException, 该id没有对应的记录");
		}
		return result;
	}

	public CommonResult<Payment> handlerFallback(Long id, Throwable t) {
		Payment payment = new Payment(id, null);
		return new CommonResult<>(444, "兜底异常handlerFallback, exception内容：" + t.getMessage(), payment);
	}

	public CommonResult<Payment> blockHandler(Long id, BlockException e) {
		Payment payment = new Payment(id, null);
		return new CommonResult<>(445, "blockHandler-sentinel限流，无此流水：blockException " + e.getMessage(), payment);
	}


	// ================openFeign

	@Resource
	private PaymentService paymentService;

	@GetMapping("/payment/{id}")
	CommonResult<Payment> getPaymentByIdUseFeign(@PathVariable("id") Long id) {
		return paymentService.getPaymentById(id);
	}
}
